//
//  AppDelegate.m
//  BulltinBoard
//
//  Created by joker on 15/6/12.
//  Copyright (c) 2015年 joker. All rights reserved.
//

#import "AppDelegate.h"
#import "bulltinBoardViewController.h"
#import "bulltinBoardListTableViewController.h"
#import "bulltinItem.h"
#import "UtilitiesFunctions.h"
#import "loginViewController.h"
#import "loginViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // Override point for customization after application launch.
    
    self.isEnterFromBackground=NO;
    
    BOOL isTest=false;
    isTest=true;
    
    if(isTest)
    {
        UILocalNotification *localNotif =
        [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        if (localNotif) {
                //获取推送信息
//            self.notificationBulltinItem=[bulltinItem new];
//            self.notificationBulltinItem.title=@"新时期通知";
//            self.notificationBulltinItem.createDate=[UtilitiesFunctions convertTimestampStringToDisplay:20070710153416];
//            self.notificationBulltinItem.message=@"全体员工：\n\t经公司研究决定，2010清明节放假及调休安排时间如下：\n\t1.端午放假时间为2010年6月22日(星期一)至2010年6月24日(星期三)";
//            
//            [self addBulltinItem: self.notificationBulltinItem whetherOrNotShowItsView:YES];
            
            application.applicationIconBadgeNumber = localNotif.applicationIconBadgeNumber-1;
        }
        [self applyLocalNotification];
    }
    else{
    
        [self applyRemoteNotification:application];
    }
    
    return YES;
}

#pragma mark -Area of Remote Notification testing

-(void)applyRemoteNotification:(UIApplication *)application{
    
    UIUserNotificationType types=UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeAlert;
    
    UIUserNotificationSettings *mySetting=[UIUserNotificationSettings settingsForTypes:types
                                                                            categories:nil];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:mySetting];
    
    [application registerForRemoteNotifications];
    NSLog(@"applyRemoteNotification function called!");
}

-(void) application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
        //注册成功会返回设备token，将这个token 传给推送服务器
    
    const void *devTokenBytes = [deviceToken bytes];
    
    NSLog(@"didRegisterForRemoteNotificationWithDeviceToker is  Called!");
        //自定义方法，将token发给服务器
        //   [self sendProviderDeviceToken:devTokenBytes]; // custom method

}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
        //向推送服务注册时如果发生错误就会进入该方法
    NSLog(@"Error in registration. Error: %@", error);
}


    //当程序运动时接收到远程通知
-(void)application: (UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
}
#pragma  mark -Area of Local Notification testing
- (void)applyLocalNotification {
        //注册通知类型
    UIUserNotificationType types=UIUserNotificationTypeAlert|UIUserNotificationTypeSound|UIUserNotificationTypeBadge;
    
        //从注册的通知类型生成通知设置
    UIUserNotificationSettings *localSettings=[UIUserNotificationSettings settingsForTypes:types categories:nil];
    
        //应用程序使用注册的通知设置进行系统注册，获取通知权限
    [[UIApplication sharedApplication] registerUserNotificationSettings:localSettings];
    
    
    NSDate *itemDate= [NSDate date];
    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
        //通知触发时间
    localNotif.fireDate = [itemDate dateByAddingTimeInterval:5];
        //默认时区
    localNotif.timeZone = [NSTimeZone defaultTimeZone];
        //通知主体文字
    localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@ in %i seconde.", nil),
                            @"The Local notification will be triggered"  , 5];
        //通知动作
    localNotif.alertAction = NSLocalizedString(@"View Details", nil);
        //通知声音
    localNotif.soundName = UILocalNotificationDefaultSoundName;
        //应用程序图标右上角角标
    localNotif.applicationIconBadgeNumber = 1;
        //设置用户信息
    
    NSDictionary *infoDict = [NSDictionary dictionaryWithObjects:@[@"清明节放假公告", @"123456789990"] forKeys:@[@"titleName",@"titleID"]];
    localNotif.userInfo = infoDict;
    
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
-(void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification completionHandler:(void (^)())completionHandler{
    NSLog(@"%@",identifier);
}

    //应用正在运行时接收到通知
-(void)application: (UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
        //获取推送的数据
    bulltinItem *newBulltinItem=[bulltinItem new];
    newBulltinItem.title=@"新放假通知";
    newBulltinItem.createDate=[UtilitiesFunctions convertTimestampStringToDisplay:1416155436];
    newBulltinItem.message=@"全体员工：\n\t经公司研究决定，2010清明节放假及调休安排时间如下：\n\t1.端午放假时间为2010年6月22日(星期一)至2010年6月24日(星期三)";
    newBulltinItem.isNewToRead=YES;
    
    if(self.isLoginSuccessfully){
        [self addBulltinItem:newBulltinItem whetherOrNotShowItsView:self.isEnterFromBackground];
    }
    
    
    application.applicationIconBadgeNumber=notification.applicationIconBadgeNumber-1;
}

-(void)addBulltinItem: (bulltinItem *)item  whetherOrNotShowItsView: (BOOL)isShow{
    
        //在这里如何获取tableListViewController实例
    if(isShow){
        UIStoryboard * storyBoard=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        bulltinBoardViewController *detailViewController=[storyBoard instantiateViewControllerWithIdentifier:@"公告详情"];
    
        detailViewController.currentItem=item;
        
        [self.tableListViewController.navigationController pushViewController:detailViewController animated:YES];
        
        self.isEnterFromBackground=NO;
       }
    [self.tableListViewController.bulltinItemsArray addObject:item];
    [self.tableListViewController sortMessageItems];
    [self.tableListViewController.tableView reloadData];
}

#pragma mark  -Other application delegate functions

- (void)applicationWillResignActive:(UIApplication *)application {
    
    self.isEnterFromBackground=YES;
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
